package com.kfm.login.handler;

import com.kfm.login.exception.LoginException;
import com.kfm.login.model.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalHandler {


    /**
     * 当项目中出现 LoginException 异常时，会进入该方法处理
     *
     * @param e
     */
    @ExceptionHandler(LoginException.class)
    public Result handleLoginException(LoginException e) {
        log.error(e.getMessage());
        return Result.failure(e.getMessage(), e.getCode());
    }

    /**
     * 当项目出现MethodArgumentNotValidException异常，会进入该方法处理
     *
     * @param e
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage());
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder message = new StringBuilder("[");
        for (ObjectError allError : allErrors) {
            message.append(allError.getDefaultMessage()).append(",");
        }
        String me = message.substring(0, message.lastIndexOf(","));
        me += "]";
        return Result.failure(me);
    }
}
